3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 namespace Wikimedia\Rdbms
;
38 class DatabaseSqlite
extends Database
{
39 /** @var string|null Directory for SQLite database files listed under their DB name */
41 /** @var string|null Explicit path for the SQLite database file */
43 /** @var string Transaction mode */
46 /** @var int The number of rows affected as an integer */
47 protected $lastAffectedRowCount;
49 protected $lastResultHandle;
54 /** @var FSLockManager (hopefully on the same server as the DB) */
57 /** @var array List of shared database already attached to this connection */
58 private $alreadyAttached = [];
60 /** @var bool Whether full text is enabled */
61 private static $fulltextEnabled = null;
63 /** @var string[] See https://www.sqlite.org/lang_transaction.html */
64 private static $VALID_TRX_MODES = [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ];
67 * Additional params include:
68 * - dbDirectory : directory containing the DB and the lock file directory
69 * - dbFilePath : use this to force the path of the DB file
70 * - trxMode : one of (deferred, immediate, exclusive)
73 public function __construct( array $p ) {
74 if ( isset( $p['dbFilePath'] ) ) {
75 $this->dbPath
= $p['dbFilePath'];
76 if ( !strlen( $p['dbname'] ) ) {
77 $p['dbname'] = self
::generateDatabaseName( $this->dbPath
);
79 } elseif ( isset( $p['dbDirectory'] ) ) {
80 $this->dbDir
= $p['dbDirectory'];
83 parent
::__construct( $p );
85 $this->trxMode
= strtoupper( $p['trxMode'] ??
'' );
87 $lockDirectory = $this->getLockFileDirectory();
88 if ( $lockDirectory !== null ) {
89 $this->lockMgr
= new FSLockManager( [
90 'domain' => $this->getDomainID(),
91 'lockDirectory' => $lockDirectory
94 $this->lockMgr
= new NullLockManager( [ 'domain' => $this->getDomainID() ] );
98 protected static function getAttributes() {
99 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
103 * @param string $filename
104 * @param array $p Options map; supports:
105 * - flags : (same as __construct counterpart)
106 * - trxMode : (same as __construct counterpart)
107 * - dbDirectory : (same as __construct counterpart)
108 * @return DatabaseSqlite
111 public static function newStandaloneInstance( $filename, array $p = [] ) {
112 $p['dbFilePath'] = $filename;
114 $p['tablePrefix'] = '';
115 /** @var DatabaseSqlite $db */
116 $db = Database
::factory( 'sqlite', $p );
124 public function getType() {
128 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
131 // Note that for SQLite, $server, $user, and $pass are ignored
133 if ( $schema !== null ) {
134 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
137 if ( $this->dbPath
!== null ) {
138 $path = $this->dbPath
;
139 } elseif ( $this->dbDir
!== null ) {
140 $path = self
::generateFileName( $this->dbDir
, $dbName );
142 throw $this->newExceptionAfterConnectError( "DB path or directory required" );
145 if ( !self
::isProcessMemoryPath( $path ) && !is_readable( $path ) ) {
146 throw $this->newExceptionAfterConnectError( 'SQLite database file is not readable' );
147 } elseif ( !in_array( $this->trxMode
, self
::$VALID_TRX_MODES, true ) ) {
148 throw $this->newExceptionAfterConnectError( "Got mode '{$this->trxMode}' for BEGIN" );
152 if ( $this->getFlag( self
::DBO_PERSISTENT
) ) {
153 // Persistent connections can avoid some schema index reading overhead.
154 // On the other hand, they can cause horrible contention with DBO_TRX.
155 if ( $this->getFlag( self
::DBO_TRX
) ) {
156 $this->connLogger
->warning( __METHOD__
. ": DBO_PERSISTENT mixed with DBO_TRX" );
158 $attributes[PDO
::ATTR_PERSISTENT
] = true;
163 $this->conn
= new PDO( "sqlite:$path", null, null, $attributes );
164 } catch ( PDOException
$e ) {
165 throw $this->newExceptionAfterConnectError( $e->getMessage() );
168 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
171 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
172 // Enforce LIKE to be case sensitive, just like MySQL
173 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
174 // Apply optimizations or requirements regarding fsync() usage
175 $sync = $this->connectionVariables
['synchronous'] ??
null;
176 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
177 $this->query( "PRAGMA synchronous = $sync", __METHOD__
, $flags );
179 } catch ( Exception
$e ) {
180 throw $this->newExceptionAfterConnectError( $e->getMessage() );
185 * @return string|null SQLite DB file path
186 * @throws DBUnexpectedError
189 public function getDbFilePath() {
190 return $this->dbPath ?? self
::generateFileName( $this->dbDir
, $this->getDBname() );
194 * @return string|null Lock file directory
196 public function getLockFileDirectory() {
197 if ( $this->dbPath
!== null && !self
::isProcessMemoryPath( $this->dbPath
) ) {
198 return dirname( $this->dbPath
) . '/locks';
199 } elseif ( $this->dbDir
!== null && !self
::isProcessMemoryPath( $this->dbDir
) ) {
200 return $this->dbDir
. '/locks';
207 * Does not actually close the connection, just destroys the reference for GC to do its work
210 protected function closeConnection() {
217 * Generates a database file name. Explicitly public for installer.
218 * @param string $dir Directory where database resides
219 * @param string|bool $dbName Database name (or false from Database::factory, validated here)
221 * @throws DBUnexpectedError
223 public static function generateFileName( $dir, $dbName ) {
225 throw new DBUnexpectedError( null, __CLASS__
. ": no DB directory specified" );
226 } elseif ( self
::isProcessMemoryPath( $dir ) ) {
227 throw new DBUnexpectedError(
229 __CLASS__
. ": cannot use process memory directory '$dir'"
231 } elseif ( !strlen( $dbName ) ) {
232 throw new DBUnexpectedError( null, __CLASS__
. ": no DB name specified" );
235 return "$dir/$dbName.sqlite";
239 * @param string $path
242 private static function generateDatabaseName( $path ) {
243 if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
244 // E.g. "file::memory:?cache=shared" => ":memory":
246 } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
247 // E.g. "file:memdb1?mode=memory" => ":memdb1:"
250 // E.g. "/home/.../some_db.sqlite3" => "some_db"
251 return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
256 * @param string $path
259 private static function isProcessMemoryPath( $path ) {
260 return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
264 * Check if the searchindext table is FTS enabled.
265 * @return bool False if not enabled.
267 public function checkForEnabledSearch() {
268 if ( self
::$fulltextEnabled === null ) {
269 self
::$fulltextEnabled = false;
270 $table = $this->tableName( 'searchindex' );
272 "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'",
274 self
::QUERY_IGNORE_DBO_TRX
277 $row = $res->fetchRow();
278 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
282 return self
::$fulltextEnabled;
286 * Returns version of currently supported SQLite fulltext search module or false if none present.
289 static function getFulltextSearchModule() {
290 static $cachedResult = null;
291 if ( $cachedResult !== null ) {
292 return $cachedResult;
294 $cachedResult = false;
295 $table = 'dummy_search_test';
297 $db = self
::newStandaloneInstance( ':memory:' );
298 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
299 $cachedResult = 'FTS3';
303 return $cachedResult;
307 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
310 * @param string $name Database name to be used in queries like
311 * SELECT foo FROM dbname.table
312 * @param bool|string $file Database file name. If omitted, will be generated
313 * using $name and configured data directory
314 * @param string $fname Calling function name
315 * @return IResultWrapper
317 public function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
318 $file = is_string( $file ) ?
$file : self
::generateFileName( $this->dbDir
, $name );
319 $encFile = $this->addQuotes( $file );
322 "ATTACH DATABASE $encFile AS $name",
324 self
::QUERY_IGNORE_DBO_TRX
328 protected function isWriteQuery( $sql ) {
329 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
332 protected function isTransactableQuery( $sql ) {
333 return parent
::isTransactableQuery( $sql ) && !in_array(
334 $this->getQueryVerb( $sql ),
335 [ 'ATTACH', 'PRAGMA' ],
341 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
344 * @return bool|IResultWrapper
346 protected function doQuery( $sql ) {
347 $res = $this->getBindingHandle()->query( $sql );
348 if ( $res === false ) {
352 $resource = ResultWrapper
::unwrap( $res );
353 $this->lastAffectedRowCount
= $resource->rowCount();
354 $res = new ResultWrapper( $this, $resource->fetchAll() );
360 * @param IResultWrapper|mixed $res
362 function freeResult( $res ) {
363 if ( $res instanceof ResultWrapper
) {
369 * @param IResultWrapper|array $res
370 * @return stdClass|bool
372 function fetchObject( $res ) {
373 $resource =& ResultWrapper
::unwrap( $res );
375 $cur = current( $resource );
376 if ( is_array( $cur ) ) {
379 foreach ( $cur as $k => $v ) {
380 if ( !is_numeric( $k ) ) {
392 * @param IResultWrapper|mixed $res
395 function fetchRow( $res ) {
396 $resource =& ResultWrapper
::unwrap( $res );
397 $cur = current( $resource );
398 if ( is_array( $cur ) ) {
408 * The PDO::Statement class implements the array interface so count() will work
410 * @param IResultWrapper|array|false $res
413 function numRows( $res ) {
414 // false does not implement Countable
415 $resource = ResultWrapper
::unwrap( $res );
417 return is_array( $resource ) ?
count( $resource ) : 0;
421 * @param IResultWrapper $res
424 function numFields( $res ) {
425 $resource = ResultWrapper
::unwrap( $res );
426 if ( is_array( $resource ) && count( $resource ) > 0 ) {
427 // The size of the result array is twice the number of fields. (T67578)
428 return count( $resource[0] ) / 2;
430 // If the result is empty return 0
436 * @param IResultWrapper $res
440 function fieldName( $res, $n ) {
441 $resource = ResultWrapper
::unwrap( $res );
442 if ( is_array( $resource ) ) {
443 $keys = array_keys( $resource[0] );
452 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
454 * @param string $name
455 * @param string $format
458 function tableName( $name, $format = 'quoted' ) {
459 // table names starting with sqlite_ are reserved
460 if ( strpos( $name, 'sqlite_' ) === 0 ) {
464 return str_replace( '"', '', parent
::tableName( $name, $format ) );
468 * This must be called after nextSequenceVal
472 function insertId() {
473 // PDO::lastInsertId yields a string :(
474 return intval( $this->getBindingHandle()->lastInsertId() );
478 * @param IResultWrapper|array $res
481 function dataSeek( $res, $row ) {
482 $resource =& ResultWrapper
::unwrap( $res );
485 for ( $i = 0; $i < $row; $i++
) {
494 function lastError() {
495 if ( !is_object( $this->conn
) ) {
496 return "Cannot return last error, no db connection";
498 $e = $this->conn
->errorInfo();
506 function lastErrno() {
507 if ( !is_object( $this->conn
) ) {
508 return "Cannot return last error, no db connection";
510 $info = $this->conn
->errorInfo();
519 protected function fetchAffectedRowCount() {
520 return $this->lastAffectedRowCount
;
523 function tableExists( $table, $fname = __METHOD__
) {
524 $tableRaw = $this->tableName( $table, 'raw' );
525 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
526 return true; // already known to exist
529 $encTable = $this->addQuotes( $tableRaw );
531 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
533 self
::QUERY_IGNORE_DBO_TRX
536 return $res->numRows() ?
true : false;
540 * Returns information about an index
541 * Returns false if the index does not exist
542 * - if errors are explicitly ignored, returns NULL on failure
544 * @param string $table
545 * @param string $index
546 * @param string $fname
547 * @return array|false
549 function indexInfo( $table, $index, $fname = __METHOD__
) {
550 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
551 $res = $this->query( $sql, $fname, self
::QUERY_IGNORE_DBO_TRX
);
552 if ( !$res ||
$res->numRows() == 0 ) {
556 foreach ( $res as $row ) {
557 $info[] = $row->name
;
564 * @param string $table
565 * @param string $index
566 * @param string $fname
569 function indexUnique( $table, $index, $fname = __METHOD__
) {
570 $row = $this->selectRow( 'sqlite_master', '*',
573 'name' => $this->indexName( $index ),
575 if ( !$row ||
!isset( $row->sql
) ) {
579 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
580 $indexPos = strpos( $row->sql
, 'INDEX' );
581 if ( $indexPos === false ) {
584 $firstPart = substr( $row->sql
, 0, $indexPos );
585 $options = explode( ' ', $firstPart );
587 return in_array( 'UNIQUE', $options );
591 * Filter the options used in SELECT statements
593 * @param array $options
596 function makeSelectOptions( $options ) {
597 foreach ( $options as $k => $v ) {
598 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
603 return parent
::makeSelectOptions( $options );
607 * @param array $options
610 protected function makeUpdateOptionsArray( $options ) {
611 $options = parent
::makeUpdateOptionsArray( $options );
612 $options = self
::fixIgnore( $options );
618 * @param array $options
621 static function fixIgnore( $options ) {
622 # SQLite uses OR IGNORE not just IGNORE
623 foreach ( $options as $k => $v ) {
624 if ( $v == 'IGNORE' ) {
625 $options[$k] = 'OR IGNORE';
633 * @param array $options
636 function makeInsertOptions( $options ) {
637 $options = self
::fixIgnore( $options );
639 return parent
::makeInsertOptions( $options );
643 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
644 * @param string $table
646 * @param string $fname
647 * @param array $options
650 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
651 if ( !count( $a ) ) {
655 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
656 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
657 $affectedRowCount = 0;
659 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
660 foreach ( $a as $v ) {
661 parent
::insert( $table, $v, "$fname/multi-row", $options );
662 $affectedRowCount +
= $this->affectedRows();
664 $this->endAtomic( $fname );
665 } catch ( Exception
$e ) {
666 $this->cancelAtomic( $fname );
669 $this->affectedRowCount
= $affectedRowCount;
671 parent
::insert( $table, $a, "$fname/single-row", $options );
678 * @param string $table
679 * @param array $uniqueIndexes Unused
680 * @param string|array $rows
681 * @param string $fname
683 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
684 if ( !count( $rows ) ) {
688 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
689 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
690 $affectedRowCount = 0;
692 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
693 foreach ( $rows as $v ) {
694 $this->nativeReplace( $table, $v, "$fname/multi-row" );
695 $affectedRowCount +
= $this->affectedRows();
697 $this->endAtomic( $fname );
698 } catch ( Exception
$e ) {
699 $this->cancelAtomic( $fname );
702 $this->affectedRowCount
= $affectedRowCount;
704 $this->nativeReplace( $table, $rows, "$fname/single-row" );
709 * Returns the size of a text field, or -1 for "unlimited"
710 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
712 * @param string $table
713 * @param string $field
716 function textFieldSize( $table, $field ) {
723 function unionSupportsOrderAndLimit() {
728 * @param string[] $sqls
729 * @param bool $all Whether to "UNION ALL" or not
732 function unionQueries( $sqls, $all ) {
733 $glue = $all ?
' UNION ALL ' : ' UNION ';
735 return implode( $glue, $sqls );
741 function wasDeadlock() {
742 return $this->lastErrno() == 5; // SQLITE_BUSY
748 function wasReadOnlyError() {
749 return $this->lastErrno() == 8; // SQLITE_READONLY;
752 public function wasConnectionError( $errno ) {
753 return $errno == 17; // SQLITE_SCHEMA;
756 protected function wasKnownStatementRollbackError() {
757 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
758 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
759 // https://sqlite.org/lang_createtable.html#uniqueconst
760 // https://sqlite.org/lang_conflict.html
764 public function serverIsReadOnly() {
765 $path = $this->getDbFilePath();
767 return ( !self
::isProcessMemoryPath( $path ) && !is_writable( $path ) );
771 * @return string Wikitext of a link to the server software's web site
773 public function getSoftwareLink() {
774 return "[{{int:version-db-sqlite-url}} SQLite]";
778 * @return string Version information from the database
780 function getServerVersion() {
781 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
787 * Get information about a given field
788 * Returns false if the field does not exist.
790 * @param string $table
791 * @param string $field
792 * @return SQLiteField|bool False on failure
794 function fieldInfo( $table, $field ) {
795 $tableName = $this->tableName( $table );
796 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
797 $res = $this->query( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
798 foreach ( $res as $row ) {
799 if ( $row->name
== $field ) {
800 return new SQLiteField( $row, $tableName );
807 protected function doBegin( $fname = '' ) {
808 if ( $this->trxMode
!= '' ) {
809 $this->query( "BEGIN {$this->trxMode}", $fname );
811 $this->query( 'BEGIN', $fname );
819 function strencode( $s ) {
820 return substr( $this->addQuotes( $s ), 1, -1 );
827 function encodeBlob( $b ) {
828 return new Blob( $b );
832 * @param Blob|string $b
835 function decodeBlob( $b ) {
836 if ( $b instanceof Blob
) {
844 * @param string|int|null|bool|Blob $s
847 function addQuotes( $s ) {
848 if ( $s instanceof Blob
) {
849 return "x'" . bin2hex( $s->fetch() ) . "'";
850 } elseif ( is_bool( $s ) ) {
852 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
853 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
854 // This is a known limitation of SQLite's mprintf function which PDO
855 // should work around, but doesn't. I have reported this to php.net as bug #63419:
856 // https://bugs.php.net/bug.php?id=63419
857 // There was already a similar report for SQLite3::escapeString, bug #62361:
858 // https://bugs.php.net/bug.php?id=62361
859 // There is an additional bug regarding sorting this data after insert
860 // on older versions of sqlite shipped with ubuntu 12.04
861 // https://phabricator.wikimedia.org/T74367
862 $this->queryLogger
->debug(
864 ': Quoting value containing null byte. ' .
865 'For consistency all binary data should have been ' .
866 'first processed with self::encodeBlob()'
868 return "x'" . bin2hex( (string)$s ) . "'";
870 return $this->getBindingHandle()->quote( (string)$s );
874 public function buildSubstring( $input, $startPosition, $length = null ) {
875 $this->assertBuildSubstringParams( $startPosition, $length );
876 $params = [ $input, $startPosition ];
877 if ( $length !== null ) {
880 return 'SUBSTR(' . implode( ',', $params ) . ')';
884 * @param string $field Field or column to cast
888 public function buildStringCast( $field ) {
889 return 'CAST ( ' . $field . ' AS TEXT )';
893 * No-op version of deadlockLoop
897 public function deadlockLoop( /*...*/ ) {
898 $args = func_get_args();
899 $function = array_shift( $args );
901 return $function( ...$args );
908 protected function replaceVars( $s ) {
909 $s = parent
::replaceVars( $s );
910 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
911 // CREATE TABLE hacks to allow schema file sharing with MySQL
913 // binary/varbinary column type -> blob
914 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
915 // no such thing as unsigned
916 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
918 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
919 // floating point types -> REAL
921 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
926 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
927 // TEXT normalization
928 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
929 // BLOB normalization
930 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
932 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
934 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
936 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
937 // binary collation type -> nothing
938 $s = preg_replace( '/\bbinary\b/i', '', $s );
939 // auto_increment -> autoincrement
940 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
941 // No explicit options
942 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
943 // AUTOINCREMENT should immedidately follow PRIMARY KEY
944 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
945 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
946 // No truncated indexes
947 $s = preg_replace( '/\(\d+\)/', '', $s );
949 $s = preg_replace( '/\bfulltext\b/i', '', $s );
950 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
951 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
952 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
953 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
954 // INSERT IGNORE --> INSERT OR IGNORE
955 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
961 public function lock( $lockName, $method, $timeout = 5 ) {
962 $status = $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout );
964 $this->lockMgr
instanceof FSLockManager
&&
965 $status->hasMessage( 'lockmanager-fail-openlock' )
967 throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
970 return $status->isOK();
973 public function unlock( $lockName, $method ) {
974 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
978 * Build a concatenation list to feed into a SQL query
980 * @param string[] $stringList
983 function buildConcat( $stringList ) {
984 return '(' . implode( ') || (', $stringList ) . ')';
987 public function buildGroupConcatField(
988 $delim, $table, $field, $conds = '', $join_conds = []
990 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
992 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
996 * @param string $oldName
997 * @param string $newName
998 * @param bool $temporary
999 * @param string $fname
1000 * @return bool|IResultWrapper
1001 * @throws RuntimeException
1003 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1004 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1005 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1006 $obj = $this->fetchObject( $res );
1008 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1011 $sql = preg_replace(
1013 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1015 $this->addIdentifierQuotes( $newName ),
1020 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1021 $this->queryLogger
->debug(
1022 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1024 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1028 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1030 // Take over indexes
1031 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1032 foreach ( $indexList as $index ) {
1033 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1037 if ( $index->unique
) {
1038 $sql = 'CREATE UNIQUE INDEX';
1040 $sql = 'CREATE INDEX';
1042 // Try to come up with a new index name, given indexes have database scope in SQLite
1043 $indexName = $newName . '_' . $index->name
;
1044 $sql .= ' ' . $indexName . ' ON ' . $newName;
1046 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1048 foreach ( $indexInfo as $indexInfoRow ) {
1049 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1052 $sql .= '(' . implode( ',', $fields ) . ')';
1054 $this->query( $sql );
1061 * List all tables on the database
1063 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1064 * @param string $fname Calling function name
1068 function listTables( $prefix = null, $fname = __METHOD__
) {
1069 $result = $this->select(
1077 foreach ( $result as $table ) {
1078 $vars = get_object_vars( $table );
1079 $table = array_pop( $vars );
1081 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1082 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1083 $endArray[] = $table;
1092 * Override due to no CASCADE support
1094 * @param string $tableName
1095 * @param string $fName
1096 * @return bool|IResultWrapper
1097 * @throws DBReadOnlyError
1099 public function dropTable( $tableName, $fName = __METHOD__
) {
1100 if ( !$this->tableExists( $tableName, $fName ) ) {
1103 $sql = "DROP TABLE " . $this->tableName( $tableName );
1105 return $this->query( $sql, $fName, self
::QUERY_IGNORE_DBO_TRX
);
1108 public function setTableAliases( array $aliases ) {
1109 parent
::setTableAliases( $aliases );
1110 foreach ( $this->tableAliases
as $params ) {
1111 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1114 $this->attachDatabase( $params['dbname'] );
1115 $this->alreadyAttached
[$params['dbname']] = true;
1119 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1120 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1121 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1123 "DELETE FROM $encTable WHERE name = $encName",
1125 self
::QUERY_IGNORE_DBO_TRX
1129 public function databasesAreIndependent() {
1136 protected function getBindingHandle() {
1137 return parent
::getBindingHandle();
1142 * @deprecated since 1.29
1144 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );